// 配置API接口地址
import config from "./config.json"
const Root = config.API_HOST;
// 引用axios
const Axios = require('axios');
function apiAxios(method, url, params, success, error) {
  let baseUrl = url.indexOf("//") >= 0 ? '' : Root;
  url = url + (url.indexOf("?") >= 0 ? '&timer=' : '?timer=') + new Date().getTime();

  Axios({
    //withCredentials: true,
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    baseURL: baseUrl,
    headers: {
      "Cache-Control": "no-cache",
      "Pragma": "no-cache"
    }
  }).then(res => {
    success(res.data);
  }).catch(err => {
    console.log(err);
    var res = {};
    if (navigator.onLine) {
      res = {
        title: '服务',
        message: '服务器忙'
      }
    } else {
      res = {
        title: '网络',
        message: '网络未连接'
      };
    }
    if (error) {
      error(res);
    } else {
      console.error(res);
    }

  });
}

// 返回在vue模板中的调用接口
export default {
  get(url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure)
  },
  post(url, params, success, failure) {
    // 对手机端做一下特殊处理
    return apiAxios('POST', url, params, success, failure)
  },
  put(url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  delete(url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  }
}
